<?php

/**
 * Implodes a list of errors into a single string.
 *
 * Takes option 'errorGlue'. Everything else is passed to the HtmlTag decorator.
 *
 * @author    Mon Zafra <monzee at gmail>
 * @copyright (c)2009 Mon Zafra
 * @category  Mz
 * @package   Mz_Decorator
 * @license   http://mz-project.googlecode.com/svn/trunk/LICENSE     MIT License
 * @version   SVN: $Id: ErrorString.php 3 2009-02-18 18:55:27Z monzee $
 */
class Mz_Decorator_ErrorString extends Zend_Form_Decorator_Abstract
{
    protected $_errorGlue = '; ';

    public function render($content)
    {
        $element = $this->getElement();
        $placement = $this->getPlacement();
        $separator = $this->getSeparator();

        $errors = $element->getMessages();
        if (empty($errors)) {
            return $content;
        }

        $glue = $this->getOption('errorGlue');
        $this->removeOption('errorGlue');
        $this->removeOption('separator');
        $this->removeOption('placement');

        $glue = null === $glue ? $this->_errorGlue : $glue;
        $errors = $this->_implodeDeep($glue, $errors);

        if (null !== $this->getOption('tag')) {
            $tagDecor = new Zend_Form_Decorator_HtmlTag($this->getOptions());
            $errors = $tagDecor->render($errors);
        }

        switch ($placement) {
            case self::APPEND:
                return $content . $separator . $errors;
                break;
            case self::PREPEND:
                return $errors . $separator . $content;
                break;
            default:
                return $errors . $separator;
                break;
        }
    }

    protected function _implodeDeep($glue, $array)
    {
        foreach ($array as &$element) {
            if (is_array($element)) {
                $element = $this->_implodeDeep($glue, $element);
            }
        }
        return implode($glue, $array);
    }

}
